package com.lazyfish.bootcm.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import com.lazyfish.bootcm.entity.Customer;
import com.lazyfish.bootcm.entity.GroupCounter;

@Repository
@Mapper
@Primary
public interface CustomerDao {
    @Select({ "<script>"
            + "select * from Customer "
            + " where 1=1  "
            + "<when test= 'source!=null'> and source=#{source} </when>"
            + "<when test= 'industry!=null'> and industry=#{industry} </when>"
            + "<when test= 'level!=null'> and level=#{level} </when>"
            + "<when test= 'pattern!=null'> and ("
	    		+ " `id` LIKE #{pattern} "
	    		+ " OR `name` LIKE #{pattern} "
	    		+ " OR `phone` LIKE #{pattern} "
	    		+ " OR `mobile` LIKE #{pattern} "
            + ") </when>"
            + " LIMIT #{pIndex}, #{pLen}"
            + "</script>"})
    List<Customer> getCustmerListBySelect(
    		@Param("source") String source, @Param("industry") String industry,
    		@Param("level") Integer level, @Param("pattern") String pattern,
    		@Param("pIndex") int pIndex, @Param("pLen") int pLen);

    @Select({ "<script>"
            + "SELECT COUNT(*) from Customer "
            + " WHERE 1=1 "
            + "<when test= 'source!=null'> and source=#{source} </when>"
            + "<when test= 'industry!=null'> and industry=#{industry} </when>"
            + "<when test= 'level!=null'> and level=#{level} </when>"
            + "<when test= 'pattern!=null'> and ("
	    		+ " `id` LIKE #{pattern} "
	    		+ " OR `name` LIKE #{pattern} "
	    		+ " OR `phone` LIKE #{pattern} "
	    		+ " OR `mobile` LIKE #{pattern} "
            + ") </when>"
            + "</script>"})
    int numberOfCustomer(
    		@Param("source") String source, @Param("industry") String industry,
    		@Param("level") Integer level, @Param("pattern") String pattern);

    @Select("SELECT `${colname}` `key`, COUNT(*) `value` FROM Customer GROUP BY `${colname}`")
    List<GroupCounter> groupCounter(String colname);
    
    @Delete("DELETE FROM Customer WHERE id=#{id}")
    int deleteCustmer(int id);
    
    @Insert("INSERT INTO Customer (name,source,industry,level,phone,mobile) VALUES (#{name},#{source},#{industry},#{level},#{phone},#{mobile})")
    int AddCustomer(Customer customer);
    
    @Update("UPDATE Customer SET name = #{name} ,industry = #{industry},level = #{level},phone = #{phone},mobile = #{mobile},source = #{source} where id =#{id}")
    int ModifyCustomer(Customer customer);
}
